<?php

namespace apps\install\models;

!defined( 'APP_ROOT' ) && exit( 'Direct Access Deny!' );

use helpers\TimeUtils;
use Phalcon\Mvc\Model;
use apps\install\utils\ReturnInfo;
use enums\SystemEnums;
use Yongze\ParseSql\Sql;


class FcmsInstall extends Model
{
    const STR_RIGHT = "<span class='glyphicon glyphicon-ok' style='color:green;'></span>";

    const STR_WRONG = "<span class='glyphicon glyphicon-remove' style='color:red;'></span>";
    
    const LOG_PATH = 'logs/fcms_install_logs.txt';
    
    /**
     * 分块每次读取多少字节数据库文件
     * $partsize
     */
//    private $partsize = 10280;
    
    
    /**
     * @author( author='New' )
     * @date( date = '2015年10月24日' )
     * @comment( comment = '检查数据库连接' )
     * @method( method = 'connectDb' )
     * @op( op = 'r' )
     */
    public function connectDb( $dbHost, $dbPort, $dbUsername, $dbPassword, $database )
    {
        $link = @mysqli_connect( $dbHost, $dbUsername, $dbPassword, $database, $dbPort );
        return $link;
    }
    
    
    /**
     * @author( author='New' )
     * @date( date = '2015年10月26日' )
     * @comment( comment = '将数据库文件导入到数据库中' )
     * @method( method = 'importDb' )
     * @op( op = 'r' )
     */
    public function importDb( $link, $file, $dbName )
    {
        $sqlCreate = 'CREATE DATABASE IF NOT EXISTS ' . $dbName . ' DEFAULT CHARSET utf8 COLLATE utf8_general_ci;';
        //数据库创建成功
        if( mysqli_query( $link, $sqlCreate ) )
        {
        	mysqli_select_db( $link, $dbName );
        	
            mysqli_query( $link, 'set names utf8' );
            
//            $lFileSize = filesize( $file );
            
            //得到每个拆分的sql语句块
//            return $this->partlyRead( $file, $lFileSize, $link, $this->partsize );

            return $this->parseSqlFileAndExecute( $file, $link );
        }
        //数据库创建失败
        else
       {
            file_put_contents( APP_ROOT . self::LOG_PATH, date( 'Y-m-d H:i:s' ) . '数据库名已存在' . PHP_EOL, FILE_APPEND );
            return $res = ReturnInfo::resInfo( 4, "<p>数据库名已存在，请删除现有同名数据库，
                           或返回上一页重新更换数据库名！&nbsp;&nbsp;" . self::STR_WRONG . "</p>" );
        }
    }

    private function parseSqlFileAndExecute( $strFile, $sqlLink )
    {
        $arrSqlLines = Sql::getSqlFromFile( $strFile );

        $iCnt = count( $arrSqlLines );
        if( $iCnt > 10 )
        {//行数不可能小于10 用0即可 当然用10也没问题

            for( $i = 0; $i < $iCnt; ++$i )
            {
                if( mysqli_query( $sqlLink, $arrSqlLines[ $i ] ) )
                {
                    if( $i != $iCnt - 1 )
                    {
                        $_SESSION[ 'percentage' ] = round( $i * 1.0 / $iCnt * 100, 2 ) . '%';
                    }
                    else
                    {
                        $_SESSION[ 'percentage' ] = '100%';
                    }

                }
                else
                {
                    return ReturnInfo::resInfo( 9, "<p>" . $arrSqlLines[ $i ] . "执行失败！&nbsp;&nbsp;" . self::STR_WRONG . "</p>" );
                }
            }

            $res[ 'status' ] = 0;
            return $res;
        }

        return ReturnInfo::resInfo( 9, "<p>" . "执行失败，文件错误！&nbsp;&nbsp;" . self::STR_WRONG . "</p>" );

    }

    
    /**
     * @author( author='New' )
     * @date( date = '2015年10月26日' )
     * @comment( comment = '将用户信息插入数据表' )    
     * @method( method = 'insertInfo' )
     * @op( op = 'r' )        
    */
    public function insertInfo( $n, $link, $dbName, $dbPrefix, $masterUsername, $masterPassword, $masterEmail )
    {

        mysqli_select_db( $link, $dbName );
        $sql = "REPLACE INTO `" . $dbName . "`.`" . $dbPrefix. "pri_users` ( `id`, `name`,`loginname`,`pwd`,`email`,`role_id`,`status`, `addtime`, `uptime` ) 
                VALUES ( " . SystemEnums::SUPER_ADMIN_ID . ", '" . $masterUsername . "','" . $masterUsername . "','" .
            $masterPassword . "','" . $masterEmail . "',1,0, '" . TimeUtils::getFullTime() . "','" . TimeUtils::getFullTime() . "');";
        
        if( mysqli_query( $link, $sql ) )
        {
            $res = ReturnInfo::resInfo( 10,
                     "<p>第二步，管理员信息写入成功！&nbsp;&nbsp;" . self::STR_RIGHT . "</p>" );
            $res[ 'n' ] = ++$n;
            file_put_contents( APP_ROOT . self::LOG_PATH, date( 'Y-m-d H:i:s' ) . ' 管理员信息写入成功'. ' $sql ' . PHP_EOL, FILE_APPEND );
        }
        else
        {
            $res = ReturnInfo::resInfo( 5,
                     "<p>第二步，管理员信息写入失败，请返回上一步重新安装！&nbsp;&nbsp;" . $sql . "&nbsp;&nbsp;" . self::STR_WRONG . "</p>" );
            file_put_contents( APP_ROOT . self::LOG_PATH, date( 'Y-m-d H:i:s' ) . '管理员信息写入失败' . PHP_EOL, FILE_APPEND );
        }
        return $res;
    }
    
}